<?php

/*
* 案件导入
*/

class CaseimportController extends Controller_Base
{
    public function init()
    {
        parent::init();
    }


    //案件上传批次列表
    public function indexAction()
    {
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $limit = intval($request->getQuery('limit', 10));
        $id = trim($request->getQuery('id', ''));
        $mediationOrganId  = intval($request->getQuery('mediationOrganId', 0));
        $assetsId  = intval($request->getQuery('assetsId', 0));
        $status = intval($request->getQuery('status', 0));
        $submitStatus = intval($request->getQuery('submitStatus', 0));
        $batchName = $request->getQuery('batchName', '');
        //检测批次解析和提交
        $where = $this->getWhere('uploadUid');
        $this->checkEntryRecord();
        $this->statistic();
        if($id){
            array_push($where,"id = ".$id);
        }
        if($status){
            array_push($where,"status = ".$status);
        }
        if($assetsId){
            array_push($where,"assetsId = ".$assetsId);
        }
        if($mediationOrganId){
            array_push($where,"mediationOrganId = ".$mediationOrganId);
        }
        if($submitStatus){
            array_push($where,"submitStatus = ".$submitStatus);
        }
        if($batchName){
            array_push($where,"batchName = '{$batchName}'");
        }
        $add_begin_end = trim($this->getRequest()->getQuery('add_begin_end', ''));
        if($add_begin_end){
            $query['add_begin_end'] = $add_begin_end;
            $date_tmp =  explode(" 到 ",$add_begin_end);
            $begin_date = $date_tmp[0];
            $end_date = $date_tmp[1];
            if (!empty($begin_date) || !empty($end_date)) {
                $begin_date = $begin_date ? $begin_date . " 00:00:00" : "";
                $end_date = $end_date ? $end_date . " 23:59:59" : "";
            }
            if ($end_date) {
                $end_date = strtotime($end_date);
                array_push($where, "addTime <= {$end_date}");

            }
            if ($begin_date) {
                $begin_date = strtotime($begin_date);
                array_push($where, "addTime >= {$begin_date}");
            }
        }


        $query = [
            'id' => $id,
            'status' => $status,
            'mediationOrganId' => $mediationOrganId,
            'assetsId' => $assetsId,
            'submitStatus' => $submitStatus,
            'add_begin_end' => $add_begin_end,
            'batchName' => $batchName,
            'limit' => $limit,
        ];

        $page = $page ? $page : 1;
        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => ($page - 1) * $limit,
            'order' => 'id DESC'
        );

        $arrList = Module_Mediate_EntryImport::getInstance()->getAllBySearch([],$seacher,true);
        $total = Module_Mediate_EntryImport::getInstance()->getAllBySearch(["count(*) as num"], ['where' => $where], true);
        $total = $total[0]['num'];
        $totalPage = ceil($total / $limit);
        //赋值调解部门
        $this ->getMediationOrgan();
        //赋值资产方
        $this ->getAssets();

        SmartyAdapter::assign('arrList', $arrList);
        SmartyAdapter::assign('disputeType',  Module_Mediate_Case::$disputeType);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('page_query', http_build_query($query));
        SmartyAdapter::assign('batchName', 'PC'.date("Ymd"));

    }

    //导入案件
    public function uploadAction()
    {
        if ($this->getRequest()->getPost()) {
            $data = $this->getRequest()->getPost('data', '');
            parse_str(urldecode($data),$data);

            if(empty($data['assetsId'])){
                AjaxTool::returnJsonData(400,'请选择资产方id');
            }
            $assetsId = $data['assetsId'];
            $assets = Module_InfoBase_Assets::getInstance()->getItemById($assetsId,true);
            if(empty($assets)){
                AjaxTool::returnJsonData(403,'找到不到对应的资产方');
            }
            if(empty($data['batchName'])){
                AjaxTool::returnJsonData(403,'请输入批次名称');
            }
            if(empty($data['disputeType'])){
                AjaxTool::returnJsonData(403,'请选择纠纷类型');
            }
            if(empty($data['caseType'])){
                AjaxTool::returnJsonData(403,'请选择案件类型');
            }
            if(empty($data['assetType'])){
                AjaxTool::returnJsonData(403,'请选择债权类型');
            }
            $dbBatchName = Module_Mediate_EntryImport::getInstance()->getItemById($data['batchName'],false,'batchName');
            if(!empty($dbBatchName)){
                AjaxTool::returnJsonData(403,'该批次名称已经存在');
            }
            $file = $this->getRequest()->getFiles('file');
            if ($file['error'] == 4) {
                AjaxTool::returnJsonData(404,'请上传文件');
            }
            $img_url = '';
            if ($file['error'] != 4) {
                $uploadFile = Lib_Upload::getInstance()->uploadFile($file, 'caseupload');
                if (!$uploadFile || $uploadFile['code']) {
                    AjaxTool::returnJsonData(405,'上传失败');
                }
                $img_url = $uploadFile['data'];
            }
            //$img_url = '/2023-04-25.xlsx';
            $file_path=  '/resource' . $img_url;
            $url = realpath(LIBRARY_DIR . '/../') . '/resource' . $img_url;
            $file_info = pathinfo($url);
            if ($file_info && strtolower($file_info['extension']) == 'csv') {
                $res = array_map('str_getcsv', file($url));
                if ($res) {
                    unset($res[0]);
                }
            } else {
                try {
                    $res = Lib_XlsxRead::getInstance()->execute($url,1);
                } catch (Exception $e) {
                    AjaxTool::returnJsonData(406,'文件格式不对'.$e);
                }
                if (empty($res)) {
                    AjaxTool::returnJsonData(407,'未发现数据');
                }
            }
            $header = $res[1];
            unset($res[1]);
            if (!$res) {
                AjaxTool::returnJsonData(408, "未发现数据");
            }
            if(empty($header)){
                 AjaxTool::returnJsonData(409, "未发现表格表头");
            }
            //先生成批次,然后再进行检查
            $entry_record_insert = [
                'assetsId'=>$assetsId,//调解部门id
                'assetsName'=>$assets['name'] ?? '',
                'mediationOrganId'=> $this->admin['mediationOrganId'] ?? '',
                'uploadUid'=> $this->admin['id'],
                'uploadName'=> $this->admin['name'],
                'status'=>1,//状态 0：未解析 1：解析中；2：解析完成；；3：解析失败
                'submitStatus'=>1,//1未提交 2提交中 3提交完成
                'addTime'=>time(),
                'updateTime'=>time(),
                'disputeType'=>$data['disputeType'],
                'caseType'=>$data['caseType'],
                'batchName'=>$data['batchName'],
                'assetType'=>$data['assetType'],
                'desc'=>'',
                'filePath'=>$file_path,//上传文件地址
            ];

            $recordId = Module_Mediate_EntryImport::getInstance()->singleInsert($entry_record_insert);
            if(!$recordId){
                AjaxTool::returnJsonData(500, "入库失败");
            }
            $this->checkCase($res,$assetsId,$header,$recordId);

        }
        AjaxTool::returnJsonData(500, "未检测到上传数据");

    }

    //检测案件
    public function checkCase($upload_case,$assetsId,$header,$record_id){
        $success = 0;
        $fail = 0;
        $fields = Lib_Var::$excel_title['caseDetail'];
        $debtorfields = Lib_Var::$excel_title['debtor'];
        foreach ($header as $key => $field){
            $header[$key] = preg_replace('/\(.*?\)|\（.*?\）/', '', $field);
        }
        $card_ids = [];
        $tidy_case = [];
        //数据整理（公债人，附加字段）
        foreach ($upload_case as $key => $case){
            //必有字段赋值
            foreach ($fields as $k => $field){
                if(in_array($k,['litigantName','cardId','telephone']) && strstr($case[$field['site']], '|')){
                    foreach (explode('|',$case[$field['site']]) as $i => $data){
                        if($k == 'cardId'){
                          $card_ids[$data] ++;
                        }
                        if($i == 0){
                            $tidy_case[$key][$k] = $data;
                        }else{
                            $tidy_case[$key]['debtor'][$i][$k] = $data;
                        }
                    }
                }else{
                    if($k == 'cardId'){
                       $card_ids[$case[$field['site']]] ++;
                    }
                    $tidy_case[$key][$k] = $case[$field['site']];
                }
                unset($case[$field['site']]);
            }
           //附加字段
            if(!empty($case)) {
                foreach ($case as $k => $val) {
                    $tidy_case[$key]['attachInfo'][] = [
                        'key' => $header[$k],
                        'val' => $val,
                    ];
                }
            }
        }
        foreach ($tidy_case as $k=>$case) {
            $insert=[
                'recordId'=>$record_id,
                'contractNo'=>$case['contractNo'],
                'status'=>2,
                'submitStatus'=>1,
                'desc'=>'',
                'addTime'=>time(),
                'updateTime'=>time(),
                'assetsId'=>$assetsId,
                'mediationOrganId'=> $this->admin['mediationOrganId'] ?? '',//调解部门id
                'caseLabel' => $card_ids[$case['cardId']] > 1 ? 1 : 0,
                'data'=>json_encode($case),
            ];
            $check_res = Lib_Var::checkData($fields,$case);
            if($check_res['error'] == 1){
                $insert['status'] = 3;
                $insert['desc'] .= $check_res['error_desc'];
            }

            //效验公债人
            if(!empty($case['debtor'])) {
                foreach ($case['debtor'] as $debtor){
                    $debtor_check_res = Lib_Var::checkData($debtorfields, $debtor);
                    if ($debtor_check_res['error'] == 1) {
                        $insert['status'] = 3;
                        $insert['desc'] .= $debtor_check_res['error_desc'];
                    }
                }
            }

            $post_data = array(
                'type' => 'Module_Task_Case',
                'method' => 'addCaseUploadDetail',
                'data' => $insert
            );
            @Module_Queue_Base::addQueue($post_data,'',1);
            if($insert['status'] == 2){
                $success++;
            }elseif($insert['status'] == 3){
                $fail++;
            }

        }

        //更新批次解析成功和失败数
        $record_updata = [
            'id' => $record_id,
            'sucessNum' => $success,
            'errorNum' => $fail,
        ];
        Module_Mediate_EntryImport::getInstance()->singleUpdate($record_updata);
        AjaxTool::returnJsonData(200,"案件批量异步解析中，稍后导入记录中查看解析结果");
    }

    //下载文件模板
    public function downTemplateAction()
    {
        $paramList = [
            [
                1 => 'TJ120012012',
                2 => 'TJ2023001',
                3 => '张三',
                4 => '440100199005251234',
                5 => '15812345678',
                6 => '平安信用卡',
                7 => '1100.10',
                8 => '12',
                9 => '2000.00',
                10 => '1000.00',
                11 => '3000.00',
                12 => '2800',
                13 => '2023/12/12',
                14 => '2020/12/12',
                15 => '2023/12/12',
                16 => '0.24',
                17 => '2023/12/12',
                18 => '张三',
                19 => '金融调解509号',
                24 => '自定义值1',
                25 => '自定义值2',
            ],
            [
                1 => 'TJ120012012',
                2 => 'TJ2023001',
                3 => '张三|李四',
                4 => '440100199005251234|440100199005254567',
                5 => '15812341234|15812345678,15556785678',
                6 => '平安信用卡',
                7 => '1100.10',
                8 => '12',
                9 => '2000.00',
                10 => '1000.00',
                11 => '3000.00',
                12 => '2800',
                13 => '2023/12/12',
                14 => '2020/12/12',
                15 => '2023/12/12',
                16 => '0.24',
                17 => '2023/12/12',
                18 => '张三',
                19 => '金融调解509号',
                24 => '自定义值1',
                25 => '自定义值2',
            ],
        ];
        $header=array_values(array_column(Lib_Var::$excel_title['caseDetail'],'name'));
        $header[] = '自定义字段1（没有请删除）';
        $header[] = '自定义字段2（没有请删除）';
        Lib_XlsxExport::getInstance()->downExcel($paramList, $header,'案件导入模板');
        exit;
    }

    //检测批次解析状态和提交状态
    protected function checkEntryRecord(){
        $record_where = [
            'status =1 or submitStatus in (1,2)',
        ];
        $records = Module_Mediate_EntryImport::getInstance()->getAllBySearch(['id','status','submitStatus','sucessNum'],['where'=>$record_where]);

        if(!empty($records)){
            foreach($records as $k=>$record){
                $up = [];

                //解析完成
                if($record['status'] == 1){
                    $analysis_where = [
                        'status in (0,1)',
                        'recordId='.$record['id'],
                    ];
                    $analysis_nofinish = Module_Mediate_ImportRecordDetail::getInstance()->getAllBySearch(['count(*) as total'],['where'=>$analysis_where],false);

                    if($analysis_nofinish['0']['total'] == 0){
                        $up['status'] = 2;
                    }
                }

                if($record['submitStatus'] == 2){

                    //提交成功和失败数
                    $submit_success = Module_Mediate_ImportRecordDetail::getInstance()->getAllBySearch(['count(*) as total'],['where'=>['recordId='.$record['id'],'submitStatus=3']],false);
                    $submit_error = Module_Mediate_ImportRecordDetail::getInstance()->getAllBySearch(['count(*) as total'],['where'=>['recordId='.$record['id'],'submitStatus=4']],false);
                    if( $record['sucessNum'] != 0 && $record['sucessNum'] <= ($submit_success['0']['total'] + $submit_error['0']['total']) ){
                        $up['submitStatus'] = 3;
                        $up['submitSuccessNum'] = $submit_success['0']['total'] ? : 0;
                        $up['submitErrorNum'] = $submit_error['0']['total'] ? : 0;
                    }

                }



                if(!empty($up)){
                    $up['id'] = $record['id'];
                    Module_Mediate_EntryImport::getInstance()->singleUpdate($up);
                }
            }
        }
    }

    //案件上传批次列表
    public function recordDetailAction()
    {
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $limit = intval($request->getQuery('limit', 10));
        $recordId = intval($request->getQuery('recordId', 0));
        $status = intval($request->getQuery('status', 0));
        $submitStatus = intval($request->getQuery('submitStatus', 0));

        $query = [
            'status' => $status,
            'submitStatus' => $submitStatus,
            'limit' => $limit,
            'recordId' => $recordId,
        ];
        $where = [];
//        $where= $this->getWhere();
        if($recordId){
            array_push($where,"recordId = {$recordId}");
        }
        if($status){
            array_push($where,"status = ".$status);
        }
        if($submitStatus){
            array_push($where,"submitStatus = ".$submitStatus);
        }
        $page = $page ? $page : 1;
        $start = ($page - 1) * $limit;
        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => $start,
            'order' => 'id DESC'
        );
        $arrList = Module_Mediate_ImportRecordDetail::getInstance()->getAllBySearch([],$seacher,true);
        $total = Module_Mediate_ImportRecordDetail::getInstance()->getAllBySearch(["count(*) as total"],['where' => $where],true);
        $total = $total[0]['total'];
        $totalPage = ceil($total / $limit);

        if(!empty($arrList)){
            foreach($arrList as $k=>$v){
                $arrList[$k]['data'] = (json_encode($this->tidyData(json_decode($v['data'], 1)), JSON_PRETTY_PRINT));
            }
        }
        SmartyAdapter::assign('arrList', $arrList);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('page_query', http_build_query($query));

    }

    //删除批次
    public function deleteRecordAction()
    {
        $request = $this->getRequest();
        $recordId = $request->getPost('recordId', 0);
        if (empty($recordId)) {
            AjaxTool::returnJsonData(400, "缺少参数");
        }
        //判断是否被提交了,提交了 就不能删除
        $entryRecord = Module_Mediate_EntryImport::getInstance()->getItemById($recordId);
        if (empty($entryRecord)) {
            AjaxTool::returnJsonData(400, "批次不存在");
        }

        if ($entryRecord['submitStatus'] != 1) {
            AjaxTool::returnJsonData(400, "已提交处理的不能删除");
        }

        Module_Mediate_EntryImport::getInstance()->beginTransaction();
        $res = Module_Mediate_EntryImport::getInstance()->deleteItemById($recordId);
        if (!$res) {
            Module_Mediate_EntryImport::getInstance()->rollback();
            AjaxTool::returnJsonData(400, "删除失败");
        }
        $res = Module_Mediate_ImportRecordDetail::getInstance()->deleteItemById($recordId, 'recordId');
        if (!$res && $res !== 0) {
            Module_Mediate_EntryImport::getInstance()->rollback();
            AjaxTool::returnJsonData(400, "详情记录删除失败");
        }
        Module_Mediate_EntryImport::getInstance()->commit();
        AjaxTool::returnJsonData(200, "操作成功");
    }

    //提交批次
    public function caseSubmitAction(){
        $recordId = $this->getRequest()->getPost('recordId', '');
        if(empty($recordId)){
            AjaxTool::returnJsonData(400, "参数异常");
        }
        //案件批次提交
        $record = Module_Mediate_EntryImport::getInstance()->getOne(['*'],['submitStatus=1',"id = {$recordId}"]);
        if($record['status'] == 1){
            AjaxTool::returnJsonData(200, '正在解析中，请解析完成后再提交');
        }
        $assets = Module_InfoBase_Assets::getInstance()->getItemById($record['assetsId']);
        if(empty($assets)){
            AjaxTool::returnJsonData(400, '找不到对应的资方');
        }
        //更新批次为提交中
        Module_Mediate_EntryImport::getInstance()->singleUpdate(["id"=>$recordId,"submitStatus"=>2]);
        $list = Module_Mediate_ImportRecordDetail::getInstance()->getAllBySearch(['*'],['where'=>["recordId = {$recordId}","status = 2","submitStatus=1"]]);
        if(!empty($list)){
            foreach($list as $k=>$v){
                $case = json_decode($v['data'],true);
                $case['importRecordId'] = $recordId;
                $case['mediationOrganId'] = $v['mediationOrganId'];
                $case['caseSource'] = 1;
                $case['detailId'] = $v['id'];
                $case['disputeType'] = $record['disputeType'];
                $case['caseType'] = $record['caseType'];
                $case['assetType'] = $record['assetType'];
                $case['batchName'] = $record['batchName'];
                $case['caseLabel'] = $v['caseLabel'];
                $data = [
                    'assets' => $assets,
                    'case' => $case,
                    'operationUid'=> $this->admin['id'],
                    'operationName'=> $this->admin['name'],
                ];
                $post_data = array(
                    'type' => 'Module_Task_Case',
                    'method' => 'saveCase',
                    'data' => $data
                );
                @Module_Queue_Base::addQueue($post_data,'',1);
            }
        }


        AjaxTool::returnJsonData(200, '提交成功'.count($list).'条');
    }

    private function tidyData($data){
        $tidyData = [];
        $fields = Lib_Var::$excel_title['caseDetail'];
        foreach ($fields as $key => $val){
            $tidyData[preg_replace('/\(.*?\)|\（.*?\）/', '', $val['name'])] = $data[$key];
        }
        if(!empty($data['debtor'])){
            $debtorfields = Lib_Var::$excel_title['debtor'];

            foreach ($data['debtor'] as $k => $debtor){
                foreach ($debtorfields as $key => $val){
                    $tidyData["公债人{$k}".preg_replace('/\(.*?\)|\（.*?\）/', '', $val['name'])] = $debtor[$key];
                }
            }
        }
        if(!empty($data['attachInfo'])){
           foreach ($data['attachInfo'] as  $attachInfo){
               $tidyData[$attachInfo['key']] = $attachInfo['val'];
           }
        }
        return $tidyData;
    }
    public function isFlashsmsAction(){
        $recordId = $this->getRequest()->getPost('id', 0);
        $flashtype = $this->getRequest()->getPost('flashtype', 0);
        $record = Module_Mediate_EntryImport::getInstance()->getItemById($recordId);
        if(empty($record)){
            AjaxTool::returnJsonData(400, '找不到相应记录');
        }
        $res = Module_Mediate_EntryImport::getInstance()->singleUpdate([
            'id' => $recordId,
            'isFlashsms' => $flashtype,
        ]);
        $type = $flashtype==1 ?'开启':"关闭";
        if($res){
            AjaxTool::returnJsonData(200, "{$type}成功");

        }
        AjaxTool::returnJsonData(400, "{$type}失败");


    }
    //统计审核
    private function statistic(){
        $records = Module_Mediate_EntryImport::getInstance()->getAllBySearch(['id','submitSuccessNum'],[ 'where'=>['submitStatus=3',"statistic = 0"]]);
        if ($records){
            $importIds = implode(',',array_column($records,'id'));
            $approvedStatistic = Module_Mediate_Case::getInstance()->getAllBySearch([
                'importRecordId',
                'count(id) as num',
                'sum(debtTotal) as debtTotal',
                'sum(debtAmount) as debtAmount'
            ],
                [
                    'where'=>[
                        "caseStatus in ('case_allocate','case_mediate','mediate_audit','close_case')",
                        "importRecordId in ($importIds)"
                    ],
                    'group'=>'importRecordId'
                ]
            );
            $approvedStatistic = array_column($approvedStatistic,NULL,'importRecordId');

            $rejectedStatistic = Module_Mediate_Case::getInstance()->getAllBySearch([
                'importRecordId',
                'count(id) as num'
            ],
                [
                    'where'=>[
                        "sysStatus =3",
                        "importRecordId in ($importIds)"
                    ],
                    'group'=>'importRecordId'
                ]
            );
            $rejectedStatistic = array_column($rejectedStatistic,NULL,'importRecordId');
            //更新
            foreach ($records as $record){
                $statistic = 0;
                $rejectedNum = empty($rejectedStatistic[$record['id']]['num']) ? 0 : $rejectedStatistic[$record['id']]['num'];
                $approvedNum = empty($approvedStatistic[$record['id']]['num']) ? 0 : $approvedStatistic[$record['id']]['num'];
                $approvedDebtAmount = empty($approvedStatistic[$record['id']]['debtAmount']) ? 0 : $approvedStatistic[$record['id']]['debtAmount'];
                $approvedDebtTotal = empty($approvedStatistic[$record['id']]['debtTotal']) ? 0 : $approvedStatistic[$record['id']]['debtTotal'];

                if($rejectedNum || $approvedNum){
                   if($record['submitSuccessNum'] == ($rejectedNum + $approvedNum)){
                        $statistic = 1;
                    }
                    Module_Mediate_EntryImport::getInstance()->singleUpdate([
                       'id' =>  $record['id'],
                       'statistic' =>  $statistic,
                       'approvedNum' =>  $approvedNum,
                       'rejectedNum' =>  $rejectedNum,
                       'approvedDebtAmount' =>  $approvedDebtAmount,
                       'approvedDebtTotal' =>  $approvedDebtTotal,
                    ]);
                }

            }
        }


    }
}
